package com.elvin.platform.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.elvin.platform.beans.*;
import com.elvin.platform.beans.Dictionary;
import com.elvin.platform.service.DeviceService;
import com.elvin.platform.service.HistoryDataService;
import com.elvin.platform.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RestController
@RequestMapping("/deviceController")
@Log4j2
@Api("设备管理")
public class DeviceController {

    @Resource
    private DeviceService service;
    @Resource
    private HistoryDataService  historyDataService;

    @ApiIgnore
    @ApiOperation(value = "获取所有设备")
    @PostMapping("/queryAll")
    public Result<Object> queryAll() {
        Result<Object> result = new Result<>();
        try {
            List<Device> selectList = service.selectList(null);
            result.success(selectList);
        } catch (Exception e) {
            log.debug(e.getMessage());
            result.fail(null, e.getMessage());
        }
        return result;
    }


    @ApiOperation(value = "分页获取所有数据")
    @PostMapping("/selectPage")
    public Result<Object> selectForPage(
            @ApiParam("当前页码") @RequestParam(value = "pageNumber", required = false)Integer pageNumber,
            @ApiParam("当前页显示条数") @RequestParam(value = "pageSize", required = false)Integer pageSize
        ) {
        Result<Object> result = new Result<>();
        try {
          int count = service.selectCount(null);
          if (count > 0) {
            List<Device> selectList = new ArrayList<>();
            if (pageNumber != null && pageSize != null) {
              Page<Device> page = new Page<>(pageNumber, pageSize);
              service.selectPage(page, null);
              selectList = page.getRecords();

            } else {
              selectList = service.selectList(null);
            }
            result.success(selectList,count);
          } else {
            result.success(null,count);
          }

        } catch (Exception e) {
            log.debug(e.getMessage());
            result.fail(null, e.getMessage());
        }
        return result;
    }


  @ApiOperation(value = "新增设备")
    @PostMapping("/insert")
    public Result<Object> insert(@RequestBody Device entity) {
        Result<Object> result = new Result<>();
        try {
            service.insert(entity);
            result.success(entity, "新增成功");
        } catch (Exception e) {
            log.debug(e.getMessage());
            result.fail(null, e.getMessage());
        }
        return result;
    }


  @ApiOperation(value = "修改设备")
    @PostMapping("/update")
    public Result<Object> update(@RequestBody Device entity) {
        Result<Object> result = new Result<>();
        try {
            service.updateById(entity);
            result.success("修改成功");
        } catch (Exception e) {
            log.debug(e.getMessage());
            result.fail(null, e.getMessage());
        }
        return result;
    }


  @ApiOperation(value = "删除设备")
    @PostMapping("/delete")
    public Result<Object> delete(@ApiParam(name="id",value="设备id",required=true) @RequestParam("id") Long id) {
        Result<Object> result = new Result<>();
        try {
            service.deleteById(id);
            result.success("删除成功");
        } catch (Exception e) {
            log.debug(e.getMessage());
            result.fail(null, e.getMessage());
        }
        return result;
    }


  @ApiOperation(value = "根据ID获取设备")
    @PostMapping("/getById")
    public Result<Object> getById(@ApiParam(name="id",value="设备id",required=true) @RequestParam("id") Long id) {
        Result<Object> result = new Result<>();
        try {
            Device entity = new Device();
            entity.setId(id);
            entity = service.selectById(entity);
            result.success(entity);
        } catch (Exception e) {
            log.debug(e.getMessage());
            result.fail(null, e.getMessage());
        }
        return result;
    }


  //云平台上报数据
    // 1、改变的设备表中的 report字段
    // 2、新增在report_data 表中
    // 3、发送微信消息
    @ApiOperation(value = "电信云平台（井盖）数据推送")
    @PostMapping("/updateReportDate")
    public Result<Object> updateReportDate(@RequestBody DeviceReport deviceReport){
        String deviceId =  deviceReport.getDeviceId();
        Result<Object> result = new Result<>();
        //转换成为JSONObject对象
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Device entity = new Device();
            HistoryData historyData = new HistoryData();
            if(StringUtils.isEmpty(deviceId)){
                result.fail(null,"deviceId不能为空");
                return result;
            }else{
                entity.setDevId(deviceId);
                String  serviceId = Long.toString(deviceReport.getServiceId());
                JSONObject payload = deviceReport.getPayload();
                JSONObject eventContent = deviceReport.getEventContent();
                long timestamp = deviceReport.getTimestamp();
                String dateString = formatter.format(timestamp);
                if(!StringUtils.isEmpty(serviceId)){
                    historyData.setType(serviceId);
                    String report = "";
                    //serviceId =="1" 存report2  serviceId =="2" 存report1
                    if (serviceId.equals("1")){
                        payload.put("report_time",dateString);
                        report = payload.toString();
                        entity.setReport2(report);
                    }else if(serviceId.equals("2")){
                        payload.put("report_time",dateString);
                        report = payload.toString();
                        entity.setReport1(report);
                    }else if(serviceId.equals("1001")){
                        eventContent.put("report_time",dateString);
                        report = eventContent.toString();
                        entity.setReport3(report);
                    }else if(serviceId.equals("1004")){
                        eventContent.put("report_time",dateString);
                        report = eventContent.toString();
                        entity.setReport4(report);
                    }
                    historyData.setReport(report);
                    historyData.setProId(deviceReport.getProductId());
                    historyData.setDevId(deviceId);
                    historyData.setDataSources("telecom_cover");
                    //dateString
                    historyData.setReportDate(formatter.parse(dateString));
                    if (!serviceId.equals("2")){
                      historyDataService.insert(historyData);
                    }
                    //3、发送微信消息
                    //1.service_id==1001 且 eventContent中的manhole_cover_position_state ==1时。
                    //2.service_id==1004 且 payload中的water_level_state ==1时
                    Map<String,Object> map = new HashMap<>();
                    map.put("devId",deviceId);
                    map.put("keyword3Value",dateString);
                    if ("1001".equals(serviceId)) {
                        if ("1".equals(String.valueOf(eventContent.get("manhole_cover_position_state")))) {
                            //发送微信
                            map.put("keyword1Value","窨井盖位置异动报警");
                            historyDataService.sendWxMsg(map);
                        }
                    }else if("1004".equals(serviceId)){
                        if ("1".equals(String.valueOf(eventContent.get("water_level_state")))) {
                            //发送微信
                            map.put("keyword1Value","窨井盖水位状态异常报警");
                            historyDataService.sendWxMsg(map);
                        }
                    }
                }
            }
            log.info(entity.toString());
            service.updateReportDate(entity);

            result.success(null);
        } catch (Exception e) {
            log.debug(e.getMessage());
            result.fail(null, e.getMessage());
        }
        return result;
    }


    @ApiIgnore
    @ApiOperation(value = "根据组织id获取当前组织及下级组织的设备信息")
    @PostMapping("/getDevicesByOrganizeIdBefore")
    public Result<Object> getDevicesByOrganizeIdBefore(@ApiParam(name="organizeId",value="组织id",required=true) @RequestParam("organizeId") Long organizeId) {
        Result<Object> result = new Result<>();
        try {
            Map<String,Object> map = new HashMap<>();
            map.put("organizeId",organizeId);
            List<Device> deviceList = service.getDevicesByOrganizeId(map);
            result.success(deviceList);
        } catch (Exception e) {
            log.debug(e.getMessage());
            result.fail(null, e.getMessage());
        }
        return result;
    }


    @ApiOperation(value = "根据组织id获取当前组织及下级组织的设备信息")
    @PostMapping("/getDevicesByOrganizeId")
    public  Object  getDevicesByOrganizeId(
            @ApiParam(name="organizeId",value="组织id",required=true) @RequestParam("organizeId") Long organizeId,
            @ApiParam("设备类型") @RequestParam(value = "devType", required = false)String devType,
            @ApiParam("设备所属平台") @RequestParam(value = "devPlatform", required = false)String devPlatform,
            @ApiParam("设备场景") @RequestParam(value = "devScenarios", required = false)Integer devScenarios,
            @ApiParam("通讯方式") @RequestParam(value = "communicationMode", required = false)String communicationMode,
            @ApiParam("是否在线") @RequestParam(value = "online", required = false)Integer online,
            @ApiParam("当前页码") @RequestParam(value = "pageNumber", required = false)Integer pageNumber,
            @ApiParam("当前页显示条数") @RequestParam(value = "pageSize", required = false)Integer pageSize
    ) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Device entity = new Device();
            entity.setOrganizeId(organizeId);
            if (online !=null){
                if(online==0){
                    entity.setOnline(false);
                }else if(online==1){
                    entity.setOnline(true);
                }else{
                    map.put("status", 1);
                    map.put("total", 0);
                    map.put("message", "online只能填写1或者0");
                    return map;
                }
            }
            entity.setDevType(devType);
            entity.setDevPlatform(devPlatform);
            entity.setDevScenarios(devScenarios);
            entity.setCommunicationMode(communicationMode);
            int total = service.selectPageCount(entity);
            if(total>0){
                PageVo pageVo = new PageVo();
                if (pageNumber !=null && pageSize !=null){
                    pageVo.setPage(pageNumber);
                    pageVo.setPageSize(pageSize);
                }else{
                    pageVo.setPage(1);
                    pageVo.setPageSize(100000000);
                }
                entity.setPageVo(pageVo);
                List<Device> list = service.selectForPage(entity);
                map.put("data", list);
            }else{
                map.put("data", null);
            }
            map.put("status", 0);
            map.put("total", total);
            map.put("message", "查询成功");
        } catch (Exception e) {
            log.debug(e.getMessage());
        }
        return map;
    }


  @ApiOperation(value = "根据场景id获取当前场景及下级场景的设备信息")
  @PostMapping("/getDevicesByDevScenariosId")
  public  Object  getDevicesByDevScenariosId(
      @ApiParam(name="devScenarios",value="场景id",required=true) @RequestParam("devScenarios") Integer devScenarios,
      @ApiParam("设备类型") @RequestParam(value = "devType", required = false)String devType,
      @ApiParam("设备所属平台") @RequestParam(value = "devPlatform", required = false)String devPlatform,
      @ApiParam("通讯方式") @RequestParam(value = "communicationMode", required = false)String communicationMode,
      @ApiParam("是否在线") @RequestParam(value = "online", required = false)Integer online,
      @ApiParam("当前页码") @RequestParam(value = "pageNumber", required = false)Integer pageNumber,
      @ApiParam("当前页显示条数") @RequestParam(value = "pageSize", required = false)Integer pageSize
  ) {
    Map<String, Object> map = new HashMap<String, Object>();
    try {
      Device entity = new Device();
      entity.setDevScenarios(devScenarios);
      if (online !=null){
        if(online==0){
          entity.setOnline(false);
        }else if(online==1){
          entity.setOnline(true);
        }else{
          map.put("status", 1);
          map.put("total", 0);
          map.put("message", "online只能填写1或者0");
          return map;
        }
      }
      entity.setDevType(devType);
      entity.setDevPlatform(devPlatform);
      entity.setCommunicationMode(communicationMode);
      int total = service.selectDevicesBydevScenariosIdCount(entity);
      if(total>0){
        PageVo pageVo = new PageVo();
        if (pageNumber !=null && pageSize !=null){
          pageVo.setPage(pageNumber);
          pageVo.setPageSize(pageSize);
        }else{
          pageVo.setPage(1);
          pageVo.setPageSize(100000000);
        }
        entity.setPageVo(pageVo);
        List<Device> list = service.selectDevicesBydevScenariosId(entity);
        map.put("data", list);
      }else{
        map.put("data", null);
      }
      map.put("status", 0);
      map.put("total", total);
      map.put("message", "查询成功");
    } catch (Exception e) {
      log.debug(e.getMessage());
    }
    return map;
  }


  /**
   * 云平台验证接口，返回收到的数据
   * @param msg
   * @return
   */
  @ApiOperation(value = "onenet平台接口验证")
  @GetMapping("/onenetReport")
  public String onenetReport(@RequestParam (value = "msg",required = false)String msg){
      log.debug("*************************onenet平台接口验证**************************************");
      log.debug(msg);
        return  msg;
  }


  @ApiOperation(value = "onenet平台数据推送")
  @PostMapping("/onenetReportOld")
  public Result<Object> onenetReportPushOld(@RequestBody DeviceVerificationNew deviceVerification){
    Result<Object> result = new Result<>();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //转换成为JSONObject对象
    String dateStr = formatter.format(new Date());
    //当params 中不存在sendStatus ，将params 保存到report1中
    Device device = new Device();
    DeviceVerificationNew.msg msg = JSONObject.parseObject(deviceVerification.getMsg(), DeviceVerificationNew.msg.class);
    JSONObject params = msg.getData().getParams();
    try {

      log.debug("*************************onenet平台数据推送1**************************************");
      log.debug(params.toString());
      log.debug("参数："+deviceVerification.toString());
      log.debug("*************************onenet平台数据推送2**************************************");
        if (params !=null){
            Object sendStatus = params.get("sendStatus");
          if (sendStatus ==null) {
            device.setImei(msg.getDeviceName());
            device.setReport1(params.toString());
            service.updateReportByImei(device);
            //新增reportData表
            HistoryData historyData = new HistoryData();
            historyData.setProId(msg.getProductId());//产品id
            historyData.setDevCode(msg.getImei());//imei
            historyData.setReportDate(formatter.parse(dateStr));
            historyData.setDataSources("onenet_pressure");
            String paramsStr = params.toString();
            historyData.setReport(paramsStr);
            String substring = params.toString().substring(paramsStr.length() - 11, paramsStr.length() - 7);
            historyData.setType(substring.equals("0000")?"0000":"0001");
            historyDataService.insert(historyData);
          }else {
            if ((int)sendStatus == 5) {
              Object confirmBody = params.get("confirmBody");
              if (confirmBody != null) {
                //存在confirmBody
                JSONObject confirmBodyObject = params.getJSONObject("confirmBody");
                JSONArray objInst = confirmBodyObject.getJSONArray("obj_inst");
                JSONArray res = objInst.getJSONObject(0).getJSONArray("res");
                JSONObject stream = res.getJSONObject(0);
                if ((int) stream.get("res_id") == 1) {
                  String rang = (String) stream.get("val");
                  device.setImei(msg.getImei());
                  device.setReport3(rang);
                  service.updateReportByImei(device);
                } else if ((int) stream.get("res_id") == 0) {
                  String alrm = (String) stream.get("val");
                  device.setImei(msg.getImei());
                  device.setReport2(alrm);
                  service.updateReportByImei(device);
                }
              }
            }
          }
        }else{
          //params等于null
          //在线离线状态
          if (msg.getData().getStatus().equals("offline")) {
            device.setImei(msg.getImei());
            device.setOnline(false);
            service.updateReportByImei(device);
          }else if (msg.getData().getStatus().equals("online")){
            device.setImei(msg.getImei());
            device.setOnline(true);
            service.updateReportByImei(device);
          }
        }
      result.success(null,"成功！");
      } catch (Exception e) {
      log.debug(e.getMessage());
      result.fail(null, e.getMessage());
    }
    return result;
  }


  @ApiOperation(value = "onenet平台数据推送最新规则")
  @PostMapping("/onenetReport")
  public Result<Object> onenetReportPush(@RequestBody DeviceVerificationNew deviceVerification){
    Result<Object> result = new Result<>();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //转换成为JSONObject对象
    String dateStr = formatter.format(new Date());
    //当params 中不存在sendStatus ，将params 保存到report1中
    Device device = new Device();
    DeviceVerificationNew.msg msg = JSONObject.parseObject(deviceVerification.getMsg(), DeviceVerificationNew.msg.class);
    JSONObject params = msg.getData().getParams();
    try {
      log.debug("*************************onenet平台数据推送1**************************************");
      log.debug(deviceVerification.toString());
      log.debug("messageType:"+msg.getMessageType());
      log.debug("*************************onenet平台数据推送2**************************************");

      if(msg.getMessageType().equals("lifecycle")){//生命周期
        //在线离线状态
        if (msg.getData().getStatus().equals("offline")) {
          device.setImei(msg.getDeviceName());
          device.setOnline(false);
          service.updateReportByImei(device);
        }else if (msg.getData().getStatus().equals("online")){
          device.setImei(msg.getDeviceName());
          device.setOnline(true);
          service.updateReportByImei(device);
        }
      }else if(msg.getMessageType().equals("notify")){//设备属性
        device.setImei(msg.getDeviceName());
        device.setReport1(params.toString());
        service.updateReportByImei(device);
        //新增reportData表
        HistoryData historyData = new HistoryData();
        historyData.setProId(msg.getProductId());//产品id
        historyData.setDevId(msg.getDeviceName());//imei
        historyData.setDevCode(msg.getDeviceName());
        historyData.setReportDate(formatter.parse(dateStr));
        historyData.setDataSources("onenet_pressure");
        String paramsStr = params.toString();
        historyData.setReport(paramsStr);
        String substring = params.toString().substring(paramsStr.length() - 11, paramsStr.length() - 7);
        historyData.setType(substring.equals("0000")?"0000":"0001");
        historyDataService.insert(historyData);

      }else if(msg.getMessageType().equals("reply")){//服务调用
        Object confirmBody = params.get("confirmBody");
        if (confirmBody != null) {
          //存在confirmBody
          JSONObject confirmBodyObject = params.getJSONObject("confirmBody");
          JSONArray objInst = confirmBodyObject.getJSONArray("obj_inst");
          JSONArray res = objInst.getJSONObject(0).getJSONArray("res");
          JSONObject stream = res.getJSONObject(0);
          if ((int) stream.get("res_id") == 1) {
            String rang = (String) stream.get("val");
            device.setImei(msg.getDeviceName());
            device.setReport3(rang);
            service.updateReportByImei(device);
          } else if ((int) stream.get("res_id") == 0) {
            String alrm = (String) stream.get("val");
            device.setImei(msg.getDeviceName());
            device.setReport2(alrm);
            service.updateReportByImei(device);
          }
        }
      }
      result.success(null,"成功！");
    } catch (Exception e) {
      log.debug(e.getMessage());
      result.fail(null, e.getMessage());
    }
    return result;
  }



  @ApiOperation(value = "根据devId和devPlatform查询数据")
  @PostMapping("/getDevicesByDevInfo")
  public  Object  getDevicesByDevInfo(
      @ApiParam(name="dev_id",value="设备id",required=true) @RequestParam("dev_id") String dev_id,
      @ApiParam(name="dev_platform",value="设备所属平台",required=true) @RequestParam("dev_platform") String dev_platform
  ) {
    Map<String, Object> map = new HashMap<String, Object>();
    try {

      EntityWrapper<Device> wrapper = new EntityWrapper<>();
      if (dev_id != null && dev_id.length() != 0) {
        wrapper.eq("dev_id", dev_id);
      }
      if (dev_platform != null && dev_platform.length() != 0) {
        wrapper.eq("dev_platform", dev_platform);
      }

      /*int count = service.selectCount(wrapper);
      if (count > 0) {
        List<Device> selectList = new ArrayList<>();
        if (pageNumber != null && pageSize != null) {
          Page<Dictionary> page = new Page<>(pageNumber,pageSize);
          service.selectPage(page,wrapper);
          selectList = page.getRecords();
        } else {
          selectList = service.selectList(wrapper);
        }
        result.success(selectList,count);
      } else {
        result.success(null,count);
      }*/
      List<Device> selectList = new ArrayList<>();
      selectList = service.selectList(wrapper);
      map.put("data", selectList);
      map.put("status", 0);
      map.put("message", "查询成功");
    } catch (Exception e) {
      log.debug(e.getMessage());
    }
    return map;
  }


}
